/*
 * Project: BoboDesignPattern
 * 
 * File Created at 2019年12月10日
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package test.practice;

import java.util.Arrays;

/**
 * @Type A20191210_heapsort
 * @Desc
 * @author 52489
 * @date 2019年12月10日
 * @Version V1.0
 */
public class A20191210_heapsort {
    public static void main(String[] args) {
        heapSort(new int[] { 3, 2, 1, 7, 8, 4, 6, 5 });
    }

    static void heapSort(int[] nums) {
        for (int i = nums.length / 2 - 1; i >= 0; i--) {
            ajustHeap1(nums, i, nums.length);
        }

        for (int i = 0; i < nums.length - 1; i++) {
            int tmp = nums[0];
            nums[0] = nums[nums.length - 1 - i];
            nums[nums.length - 1 - i] = tmp;
            ajustHeap1(nums, 0, nums.length - i - 1);
        }
        System.out.println(Arrays.toString(nums));
    }

    /**
     * @param nums
     * @param i
     * @param j
     */
    static void ajustHeap(int[] nums, int i, int j) {
        int tmp = nums[i];
        for (int k = 2 * i + 1; k < j; k = 2 * k + 1) {
            if (k + 1 < j && nums[k + 1] > nums[k]) {
                k++;
            }
            if (nums[k] > tmp) {
                nums[i] = nums[k];
                i = k;
            } else {
                break;
            }
        }
        nums[i] = tmp;
    }

    static void ajustHeap1(int[] nums, int i, int length) {
        int tmp = nums[i];
        if (2 * i + 1 > length - 1) {
            return;
        }
        int maxChildIdx = 2 * i + 1;
        if (maxChildIdx + 1 < length && nums[maxChildIdx + 1] > nums[maxChildIdx]) {
            maxChildIdx++;
        }

        if (nums[maxChildIdx] > nums[i]) {
            nums[i] = nums[maxChildIdx];
            nums[maxChildIdx] = tmp;
            ajustHeap1(nums, maxChildIdx, length);
        }

    }

}
